package github.kawaiior.botapiserver.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import github.kawaiior.botapiserver.common.ActionResponse;
import github.kawaiior.botapiserver.common.DataResponse;
import github.kawaiior.botapiserver.entity.*;
import github.kawaiior.botapiserver.mapper.*;
import github.kawaiior.botapiserver.util.CaptchaUtil;
import github.kawaiior.botapiserver.util.CookieUtil;
import github.kawaiior.botapiserver.util.StringUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BotMapper botMapper;

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private GroupUserMapper groupUserMapper;

    @Autowired
    private IpMapper ipMapper;

    @Autowired
    private KeywordMapper keywordMapper;

    public ActionResponse getLoginCode(HttpSession session) {
        return new DataResponse<>(CaptchaUtil.getCodeImg(session));
    }

    private static final ActionResponse USER_NOT_EXIST = new ActionResponse(0, "账号不存在");
    private static final ActionResponse PASSWORD_ERROR = new ActionResponse(0, "密码错误");

    public ActionResponse adminLogin(String account, String password, HttpServletResponse response) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount, account);
        User user = userMapper.selectOne(queryWrapper);
        if (user==null){
            return USER_NOT_EXIST;
        }
        if (user.getPassword().equals(password)){
            // 给用户设置一个token
            String token = StringUtil.getRandomString();
            Cookie tokenCookie = CookieUtil.genCookie("token", token);
            response.addCookie(tokenCookie);
            response.addCookie(CookieUtil.genCookie("account", account));
            user.setToken(token);
            userMapper.updateById(user);
            return ActionResponse.DEFAULT_SUCCESS_RESPONSE;
        }
        return PASSWORD_ERROR;
    }

    public ActionResponse adminUpdatePassword(String account, String password, String newPassword) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount, account);
        User user = userMapper.selectOne(queryWrapper);
        if (user==null){
            return USER_NOT_EXIST;
        }
        if (user.getPassword().equals(password)){
            // 修改密码
            user.setPassword(newPassword);
            userMapper.updateById(user);
            return ActionResponse.DEFAULT_SUCCESS_RESPONSE;
        }
        return PASSWORD_ERROR;
    }

    public ActionResponse getBots() {
        List<Bot> botList = botMapper.selectList(new QueryWrapper<>());
        return new DataResponse<>(botList);
    }

    public ActionResponse getBotInfo(String botId) {
        Bot bot = botMapper.selectOne(new QueryWrapper<Bot>().eq("bot_id", botId));
        return new DataResponse<>(bot);
    }

    public ActionResponse getBotKeywords(String botId) {
        List<Keyword> keywordList = keywordMapper.selectList(new QueryWrapper<Keyword>().eq("bot_id", botId));
        return new DataResponse<>(keywordList);
    }

    private final ActionResponse KEYWORD_EXIST = new ActionResponse(0, "关键词已存在");

    public ActionResponse addKeywordToBot(String botId, String word) {
        Keyword key = keywordMapper.selectOne(new QueryWrapper<Keyword>()
                .eq("bot_id", botId).eq("keyword", word));
        if (key!=null){
            return KEYWORD_EXIST;
        }
        keywordMapper.insert(new Keyword(botId, word));
        return ActionResponse.DEFAULT_SUCCESS_RESPONSE;
    }

    private final ActionResponse KEYWORD_NOT_EXIST = new ActionResponse(0, "关键词不存在");

    public ActionResponse removeBotKeyword(String botId, String word) {
        Keyword key = keywordMapper.selectOne(new QueryWrapper<Keyword>()
                .eq("bot_id", botId).eq("keyword", word));
        if (key==null){
            return KEYWORD_NOT_EXIST;
        }
        keywordMapper.deleteById(key);
        return ActionResponse.DEFAULT_SUCCESS_RESPONSE;
    }

    public ActionResponse getBotGroups(String botId) {
        List<BotGroup> botGroupList = groupMapper.selectList(
                new QueryWrapper<BotGroup>().eq("bot_id", botId));
        return new DataResponse<>(botGroupList);
    }

    public ActionResponse getGroupUsers(String botId, String groupId) {
        List<GroupUser> groupUserList = groupUserMapper.selectList(
                new QueryWrapper<GroupUser>()
                        .eq("bot_id", botId)
                        .eq("group_id", groupId));
        return new DataResponse<>(groupUserList);
    }

    private final ActionResponse USER_EXIST = new ActionResponse(0, "用户已存在");
    private final ActionResponse GROUP_NOT_EXIST = new ActionResponse(0, "群组不存在");

    public ActionResponse addUserToGroup(String botId, String groupId, String userId) {
        if (groupUserMapper.selectOne(new QueryWrapper<GroupUser>()
                .eq("bot_id", botId)
                .eq("group_id", groupId)
                .eq("user_id", userId)) != null){
            return USER_EXIST;
        }
        BotGroup botGroup = groupMapper.selectOne(new QueryWrapper<BotGroup>()
                .eq("bot_id", botId)
                .eq("group_id", groupId));
        if (botGroup==null){
            return GROUP_NOT_EXIST;
        }
        GroupUser user = new GroupUser("未获取昵称", groupId, botId, userId);
        groupUserMapper.insert(user);
        return ActionResponse.DEFAULT_SUCCESS_RESPONSE;
    }

    public ActionResponse removeGroupUser(String botId, String groupId, String userId) {
        GroupUser user = groupUserMapper.selectOne(new QueryWrapper<GroupUser>()
                .eq("bot_id", botId)
                .eq("group_id", groupId)
                .eq("user_id", userId));
        if (user==null){
            return USER_NOT_EXIST;
        }
        groupUserMapper.deleteById(user);
        return ActionResponse.DEFAULT_SUCCESS_RESPONSE;
    }

    public ActionResponse getBotGroupUserIps(String botId, String groupId, String userId) {
        List<Ip> ipList = ipMapper.selectList(
                new QueryWrapper<Ip>()
                        .eq("bot_id", botId)
                        .eq("group_id", groupId)
                        .eq("user_id", userId));
        if (!groupId.equals("-1")){
            List<Ip> globalIps = ipMapper.selectList(
                    new QueryWrapper<Ip>()
                            .eq("bot_id", botId)
                            .eq("group_id", "-1")
                            .eq("user_id", userId));
            ipList.addAll(globalIps);
        }
        if (!              userId.equals("-1")){
            List<Ip> groupIps = ipMapper.selectList(
                    new QueryWrapper<Ip>()
                            .eq("bot_id", botId)
                            .eq("group_id", groupId)
                            .eq("user_id", "-1"));
            ipList.addAll(groupIps);
        }
        return new DataResponse<>(ipList);
    }

    private final ActionResponse IP_EXIST = new ActionResponse(0, "IP已存在");
    private final ActionResponse NOT_IP = new ActionResponse(0, "IP格式有误");

    public ActionResponse addIpToBotUser(String botId, String groupId, String userId, String ip) {
        if (!StringUtil.isIPAddress(ip)){
            return NOT_IP;
        }
        if (ipMapper.selectOne(new QueryWrapper<Ip>()
                .eq("bot_id", botId)
                .eq("group_id", groupId)
                .eq("user_id", userId)
                .eq("ip", ip))!=null){
            return IP_EXIST;
        }
        Ip ipObj = new Ip(groupId, botId, userId, ip);
        ipMapper.insert(ipObj);
        return ActionResponse.DEFAULT_SUCCESS_RESPONSE;
    }

    private final ActionResponse IP_NOT_EXIST = new ActionResponse(0, "ip不存在");

    public ActionResponse removeBotUserIp(String botId, String groupId, String userId, String ip) {
        Ip ipObj = ipMapper.selectOne(new QueryWrapper<Ip>()
                .eq("bot_id", botId)
                .eq("group_id", groupId)
                .eq("user_id", userId)
                .eq("ip", ip));
        if (ipObj==null){
            return IP_NOT_EXIST;
        }
        ipMapper.deleteById(ipObj);
        return ActionResponse.DEFAULT_SUCCESS_RESPONSE;
    }

    private final ActionResponse BOT_NOT_EXIST = new ActionResponse(0, "bot不存在");

    public ActionResponse updateBotAtConfig(String botId, int reqAt, int respAt) {
        Bot bot = botMapper.selectOne(new QueryWrapper<Bot>().eq("bot_id", botId));
        if (bot==null){
            return BOT_NOT_EXIST;
        }
        bot.setReqAt(reqAt);
        bot.setRespAt(respAt);
        botMapper.updateById(bot);
        return ActionResponse.DEFAULT_SUCCESS_RESPONSE;
    }

}
